package nbcp.myoql.code.generator.db.mysql

import nbcp.base.comm.config
import nbcp.base.extend.HasValue
import nbcp.base.extend.Minus
import nbcp.base.utils.StringUtil
import nbcp.myoql.code.generator.removeQuoteContent

/**
 * 以后使用MySqlTableCodeTemplateData替换它。
 *
 * 表数据！
 */
class EntityDbItemData {
    var name = ""

    //原始的表注释
    var comment = ""

    //去除 （）
    val simpleComment: String
        get() {
            return comment.removeQuoteContent();
        }

    val baseType: String
        get() {
            if (columns.any { it.name == "id" }) {
                if (columns.any { it.name == "create_at" } && columns.any { it.name == "update_at" }) {
                    return "BaseSqlMarkEntity()";
                }
                return "BaseIdEntity()";
            }

            return "Serializable"
        }

    val group: String
        get() {
            // [组名]，先对表注释内容进行组名提取。
            var groups_all_value = Regex("""\[\s*([\w-_]+)\s*\]""")
                .find(
                    comment
                )
                ?.groupValues ?: listOf()

            var group_value = ""
            if (groups_all_value.size > 0) {
                group_value = groups_all_value[1];
            }

            var groups_value = group_value.split(",").map { it.trim() }.filter { it.HasValue }

            if (groups_value.any()) {
                return groups_value.first();
            }
            groups_value = name.split("_", "-");
            if (groups_value.size > 0) {
                return groups_value.first()
            }

            return "";
        }

    /**
     * 除主键，单唯一键之外的联合唯一键。
     */
    var auks = arrayOf<String>()

    val autoId:Boolean
        get(){
            return columns.any { it.autoId }
        }

    val autoNumber:Boolean
        get(){
            return columns.any { it.autoNumber }
        }

    val autoInc:Boolean
        get(){
            return columns.any { it.autoInc }
        }

    /**
     * 所有列。
     */
    var columns = mutableListOf<EntityDbItemFieldData>()

    val defineColumns: List<EntityDbItemFieldData>
        get() {
            var cs = mutableListOf<String>()
            if (columns.any { it.name == "id" }) {
                if (columns.any { it.name == "create_at" } && columns.any { it.name == "update_at" }) {
                    cs.add("create_at")
                    cs.add("update_at")
                }
                cs.add("id")
            }

            return columns.Minus(cs, { a, b -> a.name == b })
        }

    val className: String
        get() {
            var name2 = this.name
            if (name2[0].isDigit()) {
                name2 = "table_" + name2;
            }

            if (config.myoqlKeepDbName) {
                return StringUtil.splitWordParts(name2).joinToString("_")
            }

            return StringUtil.getBigCamelCase(name2)
        }
}